package coreUtils

import (
	"errors"
	"fmt"
	"strconv"
	"sync"
	"time"

	"github.com/bwmarrin/snowflake"
)

var OrderGenerator *OrderNoGenerator

type OrderNoGenerator struct {
	node *snowflake.Node
	mu   sync.Mutex
}

// InitOrderGenerator 初始化订单编号生成器
func InitOrderGenerator(workerId int64) {
	var err error
	OrderGenerator, err = NewOrderNoGenerator(workerId)
	if err != nil {
		panic("创建订单号生成器实例失败" + err.Error())
	}
}

// NewOrderNoGenerator 创建订单号生成器实例
func NewOrderNoGenerator(workerId int64) (*OrderNoGenerator, error) {
	node, err := snowflake.NewNode(workerId)
	if err != nil {
		return nil, fmt.Errorf("初始化 Snowflake 节点失败: %v", err)
	}

	return &OrderNoGenerator{
		node: node,
	}, nil
}

// Generate 生成订单号
func (g *OrderNoGenerator) Generate(pre string, length int) (string, error) {
	g.mu.Lock()
	defer g.mu.Unlock()

	// 生成雪花ID
	id := g.node.Generate()

	// 获取当前时间戳
	timestamp := time.Now().Format("20060102150405")

	preLen := len(pre) + len(timestamp)
	if preLen >= length {
		return "", errors.New("长度不正确")
	}
	idStr := strconv.FormatInt(int64(id), 10)
	needLen := length - preLen
	if len(idStr) < needLen {
		idStr = fmt.Sprintf("%0"+strconv.Itoa(needLen)+"d", id)
	} else {
		idStr = idStr[len(idStr)-(needLen):]
	}

	// 组合订单号：前缀 + 时间戳 + 雪花ID
	orderNo := fmt.Sprintf("%s%s%s", pre, timestamp, idStr)

	return orderNo, nil
}
